package org.backend.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.backend.mapper.MessageMapper;
import org.backend.pojo.entity.Message;
import org.backend.pojo.entity.Product;
import org.backend.pojo.entity.WxUser;
import org.backend.pojo.vo.MessageVO;
import org.backend.repository.MessageRepository;
import org.backend.repository.ProductRepository;
import org.backend.repository.UserRepository;
import org.backend.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ProductRepository productRepository;

    /**
     * 微信小程序端获取历史消息记录
     * @param openid
     * @return
     */
    @Override
    public List<MessageVO> getHistoryMessageToMiniProgram(String openid) {
        List<Message> list = messageRepository.getHistoryMessageByOpenid(openid);
        if (list == null || list.isEmpty()) {
            throw new IllegalArgumentException("未成功获取历史消息");
        }
        log.info(list.toString());
        List<MessageVO> voList = new ArrayList<>();
        for (Message message : list) {
            MessageVO messageVO = new MessageVO();
            MessageVO.Data1 data = new MessageVO.Data1();
            Product product = productRepository.getProductById(message.getProductId());
            log.info(message.toString());
            WxUser wxUser = userRepository.getByOpenid(message.getSenderOpenid());
            data.setBuyerName(wxUser.getName());
            data.setProductId(message.getProductId());
            data.setProductName(product.getName());
            String formattedTime = message.getSendTime().toString().replace("T", " ");
            data.setCreateTime(formattedTime);
            messageVO.setData(data);
            messageVO.setType(message.getType());

            voList.add(messageVO);
        }
        return voList;
    }
}
